package com.atguigu.gulimall.auth.service.impl;

import com.atguigu.gulimall.auth.feign.SmsFeignService;
import com.atguigu.gulimall.auth.constant.PhoneCode;
import com.atguigu.gulimall.auth.service.SmsService;
import com.atguigu.gulimall.common.exception.BizCodeEnum;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private SmsFeignService smsFeignService;

    @Override
    public boolean sendCode(String phone) {
        String resultCode = redisTemplate.opsForValue().get(PhoneCode.SMS_PHONE_PREFIX + phone);
        if (StringUtils.isNotEmpty(resultCode)) {
            String[] split = resultCode.split("_");
            long start = Long.parseLong(split[1]);
            long end = System.currentTimeMillis();
            if ((end - start) / 1000 < 60) {
                // 表示没超过60s
                return false;
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5) + "_" + System.currentTimeMillis();
        // 将 code 保存到 redis中
        redisTemplate.opsForValue().set(PhoneCode.SMS_PHONE_PREFIX + phone, code, 1, TimeUnit.HOURS);

        // 判断验证码是否正确
        smsFeignService.codeflag(phone, code);
        return true;
    }
}
